﻿#include "LoadSettingFileData.h"
#include <qfile.h>
#include <QTextStream>
#include <qxml.h>
#include <QtXml/QtXml>
#include "dXml.h"
#include <XmlDataUnit.h>
#include <XmlDataDoc.h>

int* lThread::LoadSettingFileData::threadRunStatus(int* status) {
	static int runStatus = 0;
	if( status != Q_NULLPTR )
		runStatus = *status;
	return &runStatus;
}

void lThread::LoadSettingFileData::releaseResources( ) {
	int status = 0xf1;
	while( true ) {
		QMutexLocker locker(q_mutex);
		bool isRunning = this->isRunning( );
		if( !isRunning )
			break;
		int runStatus = *threadRunStatus( );
		if( !runStatus )
			threadRunStatus(&status);
	}
	this->quit( );
}

lThread::LoadSettingFileData::LoadSettingFileData(const SigInstance* sigInstance
	, QWidget* paren): QThread(paren),
	m_sigInstance(sigInstance) {
	q_mutex = new QMutex;
}

lThread::LoadSettingFileData::~LoadSettingFileData( ) {
	this->releaseResources( );
	delete q_mutex;
}

void lThread::LoadSettingFileData::stopTask( ) {
	// 释放资源
	this->releaseResources( );
}

void lThread::LoadSettingFileData::startTask( ) {
	// 释放资源
	this->releaseResources( );
	this->start( );
}

void lThread::LoadSettingFileData::setTask(LoadSettingType taskType
	, QString path
	, dXml::XmlDataUnit* obj) {
	this->taskType = taskType;
	this->taskDir = path;
	this->taskPath = path + "/" + QFileInfo(path).baseName( ) + "setting.xml";
	this->taskDoc = obj;
}

void lThread::LoadSettingFileData::runReadTask(dXml::XmlDataUnit* saveToData
	, QString& outPITarget
	, QString& outPIData
	, const QString& file) {
	dXml::readXmlFile(saveToData, outPITarget, outPIData, file);
}

void lThread::LoadSettingFileData::runWriteTask(dXml::XmlDataUnit* saveToData
	, const QString& file) {
	saveToData->save(file);
}

void lThread::LoadSettingFileData::run( ) {
	if( taskType == NONE || taskPath.isEmpty( ) ) {
		return;
	} else {
		QString outPITarget, outPIData;
		switch( this->taskType ) {
		case READ:
			runReadTask(taskDoc, outPITarget, outPIData, taskPath);
			emit readOverTask(this->taskDoc);
			break;
		case WRITE:
			runWriteTask(taskDoc, taskPath);
			emit writeOverTask(this->taskDoc);
			break;
		}
	}
}
